/**
 * @Description 观察者模式
 * @date 2020-11-18
 * @param Observer: 观察者
 * @param Subject: 订阅事件
 * @returns {any}
 */

class Observer {
    constructor(name) {
        this.name = name;
    }

    update () {
        console.log(`${this.name} update`)
    }
}

class Subject {
    constructor() {
        this.subs = [];
    }

    add (observer) {
        this.subs.push(observer);
    }

    notify () {
        this.subs.forEach(item => {
            item.update();
        });
    }
}

const sub = new Subject();
const ob1 = new Observer('jack');
const ob2 = new Observer('ob2');

// 观察者订阅目标
sub.add(ob1);
sub.add(ob2);

// 目标触发事件
sub.notify();